package com.sanq.product.utils;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.PutObjectRequest;
import com.sanq.product.config.utils.date.DateUtil;
import com.sanq.product.config.utils.string.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by XieZhyan on 2018/11/23.
 */
@Component
public class File2Oss {

    private static File2Oss instance;

    private File2Oss() {
    }

    private OSSClient mOSSClient;

    public static File2Oss getInstance() {
        if (instance == null) {
            synchronized (File2Oss.class) {
                if (instance == null) {
                    instance = new File2Oss();
                }
            }
        }
        return instance;
    }

    @Value("${oss.endpoint}")
    public String ossEndPoint;

    @Value("${oss.AccessKeyId}")
    public String ossAccessKeyId;

    @Value("${oss.AccessKeySecret}")
    public String ossAccessKeySecret;
    
    @Value("${oss.show}")
    public String ossShow;
    
    @Value("${oss.bucketName}")
    public String ossBucketName;
    


    private OSSClient init() {
        ClientConfiguration conf = new ClientConfiguration();
        // 开启支持CNAME。CNAME是指将自定义域名绑定到存储空间上。
        conf.setSupportCname(true);
        return new OSSClient(ossEndPoint,
                    ossAccessKeyId,
                    ossAccessKeySecret,
                    conf);
    }

    //单文件上传
    //通过文件流
    public String uploadToOSSByIs(String fileName, InputStream is) {
        mOSSClient = init();
        //设置文件名称
        fileName = changeFileName(fileName);
        //上传文件夹
        String dirPath = DateUtil.date2Str(new Date(), "yyyy/MM/dd");
        try {
            mOSSClient.putObject(ossBucketName, dirPath + "/" + fileName, is);
            return dirPath + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mOSSClient != null)
                mOSSClient.shutdown();
        }
        return null;
    }

    public List<String> uploadListFileToOSS(String[] fileNames, InputStream[] ises) {
        mOSSClient = init();
        List<String> fileUrls = new ArrayList<>();

        try {
            ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue(
                    Arrays.asList(fileNames));
            ConcurrentLinkedQueue<InputStream> streamConcurrentLinkedQueue = new ConcurrentLinkedQueue<>(
                    Arrays.asList(ises));
            Iterator<InputStream> inputStreamss = streamConcurrentLinkedQueue.iterator();
            ConcurrentLinkedQueue c = new ConcurrentLinkedQueue();
            String dirPath = DateUtil.date2Str(new Date(), "yyyy/MM/dd");
            for (Iterator<String> iterator = concurrentLinkedQueue.iterator();
                 iterator.hasNext() && inputStreamss.hasNext(); ) {
                //设置文件名称
                String fileName = changeFileName(iterator.next());
                //上传文件夹
                mOSSClient.putObject(new PutObjectRequest(ossBucketName,
                            dirPath + "/" + fileName, inputStreamss.next()));

                fileUrls.add(dirPath + "/" + fileName);
            }
            return fileUrls;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mOSSClient != null)
                mOSSClient.shutdown();
        }
        return null;
    }

    public List<String> deleteFileByOSS(List<String> files) {
        mOSSClient = init();
        try {
            DeleteObjectsResult deleteObjectsResult =
                        mOSSClient.deleteObjects(new DeleteObjectsRequest(ossBucketName).withKeys(files));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            return deletedObjects;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mOSSClient != null)
                mOSSClient.shutdown();
        }
        return null;
    }

    private String changeFileName(String fileName) {
        String uuid = StringUtil.uuid();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        return uuid + suffix;
    }

    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
//        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
//        // 生成URL
//        URL url = mOSSClient.generatePresignedUrl(ossBucketName, key, expiration);
//        if (url != null) {
//            return url.toString();
//        }
//        return null;
        return ossShow + "/" + key;
    }
}
